import { FeatherX } from 'cui-vue-icons/feather';
import { HTMLAttributes, computed, defineComponent, ref, watch } from 'vue';

export interface TagProps extends HTMLAttributes {
    theme?: 'primary'|'danger'|'warning'|'success'|'info'|'magenta'|'red'|'volcano'|'orange'|'gold'|'yellow'|'lime'|'green'|'cyan'|'blue'|'geekblue'|'purple',
    value?: any,
    circle?: boolean,
    size?: 'small'|'large'|'xlarge',
    avatar?: any,
    onBeforeClose?: (e: any) => boolean,
    closable?: boolean,
    modelValue?: boolean
    border?: boolean,
}

export default defineComponent({
    name: 'Tag',
    props: ['theme', 'value', 'circle', 'size', 'avatar', 'onBeforeClose', 'onClose', 'closable', 'modelValue', 'border'],
    emits: ['update:modelValue', 'close'],
    setup (props: TagProps, {emit, slots}) {
        const value = () => props.value ?? '';

        const classList = computed(() => ({
            'cm-tag': true,
            [`cm-tag-${props.theme}`]: props.theme,
            'cm-tag-has-badge': value() !== '',
            'cm-tag-border': props.border,
            'cm-tag-circle': !value() && props.circle,
            [`cm-tag-${props.size}`]: props.size,
            'cm-tag-has-avatar': props.avatar
        }));

        const visible = ref(props.modelValue ?? true);

        watch(() => props.modelValue, (val) => {
            visible.value = val ?? true;
        });

        const _onClose = (e: any) => {
            if (props.onBeforeClose) {
                const ret = props.onBeforeClose(e);
                if (ret) {
                    doClose(e);
                }
            } else {
                doClose(e);
            }
        };

        const doClose = (e: any) => {
            visible.value = false;
            emit('update:modelValue', false);
            emit('close', e);
        };

        return () =>
            visible.value
                ? <div class={classList.value}>
                    <div class="cm-tag-content">
                        {props.avatar}
                        <div class="cm-tag-text">{slots.default?.()}</div>
                        {
                            props.closable
                                ? <FeatherX class="cm-tag-close" size={12} onClick={_onClose}/>
                                : null
                        }
                    </div>
                    {
                        value() !== '' ? <span class="cm-tag-badge">
                            <span class="cm-tag-badge-text">{value()}</span>
                        </span> : null
                    }
                </div>
                : null;
    }
});
